package com.zsyg.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.zsyg.common.util.RedisUtil;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceAutoConfiguration {

//    @Resource
//    DataSourceProperties properties;

    @Bean
    public RedisUtil redisUtil() {
        RedisUtil redisUtil = new RedisUtil();
        return redisUtil;
    }

    @Bean
    public DataSource dataSource() {
        //可以在此处调用相关接口获取数据库的配置信息进行 DataSource 的配置
//        DruidDataSource dataSource = new DruidDataSource();
//        dataSource.setUrl(properties.getUrl());
//        dataSource.setUsername(properties.getUsername());
//        dataSource.setPassword(properties.getPassword());
//        dataSource.setDriverClassName(properties.getDriverClassName());
        Object data = redisUtil().getObject("dataSource");
        Map<String,String> dataSourceMap = new HashMap<>();
        if(data == null){
            dataSourceMap.put("url","jdbc:mysql://192.168.1.105:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false");
            dataSourceMap.put("username","root");
            dataSourceMap.put("password","root");
            dataSourceMap.put("driver","com.mysql.jdbc.Driver");
            redisUtil().setObject("dataSource",dataSourceMap);
        }else {
            dataSourceMap = (Map<String,String>) data;
        }
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(dataSourceMap.get("url"));
        dataSource.setUsername(dataSourceMap.get("username"));
        dataSource.setPassword(dataSourceMap.get("password"));
        dataSource.setDriverClassName(dataSourceMap.get("driver"));
        return dataSource;
    }


}
